Page({
  data: {
    messages: [] as Array<{ id: number; speaker: string; content: string; createdAt: string }>,
    inputValue: "",
    userInfo: {} as Partial<WechatMiniprogram.UserInfo>, // Use Partial for userInfo as it might be initially empty
    scrollIntoView: "", // 用于自动滚动到最新消息
    inputFocus: false, // 控制输入框聚焦
  },

  onLoad() {
    this.fetchMessages();
    const storedUserInfo = wx.getStorageSync("userInfo") as WechatMiniprogram.UserInfo;
    if (storedUserInfo && storedUserInfo.nickName) { // Check if nickName exists to ensure it's valid UserInfo
      this.setData({ userInfo: storedUserInfo });
    }
  },

  onShow() {
    // 页面显示时自动滚动到底部
    if (this.data.messages.length > 0) {
      const lastMessage = this.data.messages[this.data.messages.length - 1];
      this.setData({
        scrollIntoView: `msg-${lastMessage.id}`
      });
    }
  },

  fetchMessages() {
    // 显示加载状态
    wx.showLoading({
      title: '加载中',
      mask: true
    });
    
    wx.request({
      url: "http://127.0.0.1:5000/api/getChatRecords", // Ensure this matches your app.globalData.apiBaseUrl if used elsewhere
      method: "GET",
      success: (res: WechatMiniprogram.RequestSuccessCallbackResult<unknown>) => {
        if (res.statusCode === 200) {
          // Safely check if res.data is an array before calling .map
          if (Array.isArray(res.data)) {
            const messagesData = res.data as Array<{ id: number; speaker: string; content: string; created_at: string }>;
            const formattedMessages = messagesData.map((msg) => ({
              id: msg.id,
              speaker: msg.speaker,
              content: msg.content,
              // Ensure msg.created_at is a string that new Date() can parse reliably.
              // Backend should ideally send ISO 8601 format (YYYY-MM-DDTHH:MM:SSZ or YYYY-MM-DDTHH:MM:SS)
              createdAt: this.formatTime(msg.created_at) 
            }));
            
            this.setData({
              messages: formattedMessages
            }, () => {
              // 设置完消息后滚动到最新消息
              if (formattedMessages.length > 0) {
                const lastMessage = formattedMessages[formattedMessages.length - 1];
                this.setData({
                  scrollIntoView: `msg-${lastMessage.id}`
                });
              }
            });
          } else {
            console.error("Failed to fetch messages: res.data is not an array", res.data);
            this.setData({ messages: [] }); // Clear messages or handle error appropriately
            wx.showToast({ title: "获取消息失败", icon: "none" });
          }
        } else {
          console.error("Failed to fetch messages, status code:", res.statusCode, res.data);
          wx.showToast({ title: "获取消息失败", icon: "none" });
        }
      },
      fail: (err) => {
        console.error("Failed to fetch messages request error", err);
        wx.showToast({ title: "网络请求失败", icon: "none" });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  // Use WechatMiniprogram.CustomEvent for input events
  onInputChange(e: WechatMiniprogram.CustomEvent<{value: string}>) {
    this.setData({ inputValue: e.detail.value });
  },

  sendMessage() {
    if (!this.data.inputValue.trim()) return;
  
    const userInfo = this.data.userInfo || wx.getStorageSync("userInfo") as WechatMiniprogram.UserInfo;
    const speaker = userInfo.nickName ? userInfo.nickName : "未登录用户";
    
    // 显示发送中状态
    wx.showLoading({
      title: '发送中',
      mask: true
    });
  
    wx.request({
      url: "http://127.0.0.1:5000/api/addChatRecord",
      method: "POST",
      data: { speaker: speaker, content: this.data.inputValue },
      success: (res: WechatMiniprogram.RequestSuccessCallbackResult<unknown>) => {
        // Backend for addChatRecord returns 201 Created
        if (res.statusCode === 201) { 
          this.fetchMessages(); 
          this.setData({ 
            inputValue: "",
            inputFocus: true // 保持输入框聚焦
          });
          
        } else {
          console.error("Failed to send message, status code:", res.statusCode, res.data);
          wx.showToast({ title: "发送失败", icon: "none" });
        }
      },
      fail: (err) => {
        console.error("Failed to send message request error", err);
        wx.showToast({ title: "发送请求失败", icon: "none" });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },

  deleteMessage(e: WechatMiniprogram.TouchEvent) {
    const recordId = e.currentTarget.dataset.id as number;
    wx.showModal({
      title: "确认删除",
      content: "确定要删除这条消息吗？",
      success: (modalRes) => {
        if (modalRes.confirm) {
          wx.showLoading({
            title: '删除中',
            mask: true
          });
          
          wx.request({
            url: "http://127.0.0.1:5000/api/deleteChatRecord",
            method: "POST",
            data: { id: recordId },
            success: (res: WechatMiniprogram.RequestSuccessCallbackResult<unknown>) => {
              // Backend for deleteChatRecord returns 200 OK on success
              if (res.statusCode === 200) {
                this.fetchMessages();
                
              } else {
                console.error("Failed to delete message, status code:", res.statusCode, res.data);
                wx.showToast({ title: "删除失败", icon: "none" });
              }
            },
            fail: (err) => {
              console.error("Failed to delete message request error", err);
              wx.showToast({ title: "删除请求失败", icon: "none" });
            },
            complete: () => {
              wx.hideLoading();
            }
          });
        }
      }
    });
  },

  // Robust time formatting
  formatTime(dateString: string): string {
    if (!dateString) return "时间未知";
    try {
      // Attempt to make the date string more universally parsable by JavaScript's Date constructor
      // Handles "YYYY-MM-DD HH:MM:SS" by replacing space with 'T'
      // Handles potential timezone information if backend provides it (e.g., Z for UTC)
      let parsableDateString = dateString;
      if (typeof dateString === "string" && dateString.includes(" ") && !dateString.includes("T")) {
        parsableDateString = dateString.replace(" ", "T");
      }
      // Further iOS compatibility for "YYYY-MM-DDTHH:MM:SS" by replacing dashes in date part if needed for new Date()
      // However, new Date() is generally good with ISO 8601 (YYYY-MM-DDTHH:MM:SS)
      // If backend returns RFC 822 like "ddd, dd MMM yyyy HH:mm:ss GMT", new Date() handles it.

      const date = new Date(parsableDateString);
      if (isNaN(date.getTime())) {
        console.warn(`formatTime: Failed to parse date string: '${dateString}' (tried as '${parsableDateString}')`);
        return dateString; // Return original string if parsing fails
      }

      const year = date.getFullYear();
      const month = ("0" + (date.getMonth() + 1)).slice(-2);
      const day = ("0" + date.getDate()).slice(-2);
      const hours = ("0" + date.getHours()).slice(-2);
      const minutes = ("0" + date.getMinutes()).slice(-2);
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (error) {
      console.error(`formatTime: Error formatting date string: '${dateString}'`, error);
      return dateString; // Return original string on error
    }
  }
});
